package com.imooc.framework.web;

import com.imooc.framework.thread.CountDownLatchDemo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;

@RestController()
@RequestMapping("countDownLatch")
public class CountDownLatchController {

    @RequestMapping("getData")
    public void getData() throws InterruptedException {
        go();
    }



    private void go() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        Task task1 = new Task(countDownLatch,1000);
        Thread t1 = new Thread(task1, "thread1");
        t1.start();
        Task task2 = new Task(countDownLatch,5000);
        Thread t2 = new Thread(task2, "thread2");
        t2.start();
        countDownLatch.await();
        System.out.println("所有线程已到达,主线程开始执行");

    }

    class Task implements Runnable {

        private Integer count = 10;

        private CountDownLatch countDownLatch;

        private Integer awaitTime;

        public Task(CountDownLatch countDownLatch,Integer awaitTime) {
            this.countDownLatch = countDownLatch;
            this.awaitTime = awaitTime;
        }

        @Override
        public void run() {

            try {
                Thread.sleep(awaitTime);
                System.out.println(Thread.currentThread().getName() + ":" + countDownLatch.getCount());
                count--;
                System.out.println("count: " + count);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            countDownLatch.countDown();
        }
    }

//    static Counter counter = new Counter();

    @RequestMapping("increment")
    public void increment()  {
        Counter counter = new Counter();
        counter.increment();
    }
}
